package me.toalec.RankUp;

import java.util.HashMap;

import me.toalec.RankUp.Permissions.PermissionsManager;
import me.toalec.RankUp.util.Utility;

import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerListener;

public class WordTrigger extends PlayerListener{
	
	WordTrigger(ConfigManager config, PermissionsManager pm){
		this.config = config;
		this.pm = pm;
	}
	
	public void onPlayerChat(PlayerChatEvent event){
		
		HashMap<String, String> word_package = config.getAllWord_PackageHashMap();
		if((!event.getMessage().equals("")) && word_package.containsKey(event.getMessage())){
			String groupName = word_package.get(event.getMessage());
			if(config.getBoolean(groupName + ".rankup_word_enabled")){
				String startingGroup = config.getString(groupName + ".startingGroup");
				String endingGroup = config.getString(groupName + ".endingGroup");
				
				Player player = event.getPlayer();
				
				if( pm.isValidGroup(startingGroup, player) && pm.isValidGroup(endingGroup, player) ){
					if( pm.isValidPlayer(player.getName(), player) && pm.getGroupName(player.getName(), player).contains(startingGroup)){
						
						pm.removeGroup(player.getName(), player, startingGroup);
						pm.addGroup(player.getName(), player, endingGroup);
						Utility.messagePlayer(player, "Your rank has successfully changed to " + endingGroup + ".");
						
					}else
						Utility.messagePlayer(player, "You are not in the correct Rank to use this word.");
				}else{
					Utility.messagePlayer(player, "There is an issue with config.yml. Ask those who can, to check it.");
				}
		
				event.setCancelled(true);
			}
		}
	}
	
	private ConfigManager config;
	private PermissionsManager pm;
}
